/*
** my_str_to_wordtab.c for minishell2 in /home/lingla_j/work/tutorat/env
** 
** Made by julien linglain
** Login   <lingla_j@epitech.net>
** 
** Started on  Tue Feb 28 18:09:13 2012 julien linglain
** Last update Thu Apr 12 00:37:03 2012 julien linglain
*/

#include        <stdio.h>
#include        <unistd.h>
#include        <stdlib.h>
#include	<string.h>
#include        <sys/types.h>
#include	"mysh.h"

void	str_to_wordtab3(t_stw *var, char *s)
{
  while (s[var->i] != '\0' && !is_space(s[var->i]))
    var->i++;
  if ((var->i - var->j) != 0)
    {
      var->tab[var->wd] = xmalloc(sizeof(char) * (var->i - var->j + 1));
      strncpy(var->tab[var->wd], &s[var->j], var->i - var->j);
      var->tab[var->wd][var->i - var-> j] = '\0';
      var->wd++;
    }
}

void	str_to_wordtab2(t_stw *var, char *s)
{
  var->j++;
  var->i++;
  while (s[var->i] != '\0' && s[var->i] != '"')
    var->i++;
  var->i++;
  if ((var->i - var->j) != 0)
    {
      var->tab[var->wd] = xmalloc(sizeof(char) * (var->i - var->j + 1));
      strncpy(var->tab[var->wd], &s[var->j], var->i - var->j - 1);
      var->tab[var->wd][var->i - var->j]  = '\0';
      var->wd++;
    }
}

char	**str_to_wordtab(char *s, int len)
{
  t_stw	var;

  var.i = 0;
  var.wd = 0;
  var.tab = xmalloc(sizeof(char*) * len);
  while (s[var.i] != '\0')
    {
      while (s[var.i] != '\0' && is_space(s[var.i]))
        var.i++;
      var.j = var.i;
      if (s[var.j] == '"')
        str_to_wordtab2(&var, s);
      else
        str_to_wordtab3(&var, s);
    }
  var.tab[var.wd] = NULL;
  return (var.tab);
}

int	check_quote(char *s)
{
  int	quote;
  int	i;

  i = 0;
  while (s[i] != '\0')
    {
      if (s[i] == '"')
        quote++;
      i++;
    }
  if (quote % 2 == 1)
    return (1);
  else
    return (0);
}

char	**my_str_to_wordtab(char *s)
{
  char	**tab;
  int	len;

  if (check_quote(s) == 1)
    {
      len = countword2(s);
      tab = str_to_wordtab(s, len);
    }
  else
    {
      len = countword(s);
      tab = str_to_wordtab(s, len);
    }
  return (tab);
}
